import React, { useState } from 'react';
import _ from 'lodash';

const UseState = () => {
  // 单个变量
  const [count, setCount] = useState(0)
  const hanldClick = () => {
    setCount(count + 1)
  }
  // 对象
  const [form, setForm] = useState({
    name: 'Tom',
  })
  const ChangeForm = () => {
    setForm({
      ...form,
      name: 'Jerry',
    })
  }
  // 数组
  const [commentList, setCommentList] = useState([
    { id: 1, name: 'one', type: '111' },
    { id: 2, name: 'two', type: '222' },
    { id: 3, name: 'three', type: '333' },
  ])
  const changeArr = () => {
    // 删除元素
    setCommentList(commentList.filter(p => p.id !== 1))

    // 添加元素
    // setCommentList([...commentList, { id: 4, name: 'four' }])
    // setCommentList(prev => [...prev, { id: 4, name: 'four' }])

    // 修改
    /*
    1.
    setCommentList(commentList.map(obj => {
      if (obj.id === 1) {
        return { ...obj, name: 'update one' }
      }
      return obj
    }));
    */

    /*
    2.
    setCommentList(prev => prev.map(obj => {
      if (obj.id === 1) {
        return { ...obj, name: 'Updated one' };
      }
      return obj;
    }));
    */
  }
  // tab切换
  const [type, setType] = useState('111')
  const changeType = (id) => {
    setType(id)
    // 排序
    setCommentList([...commentList].sort((a, b) => b.id - a.id))
    // setCommentList(_.orderBy(commentList, 'id', 'desc'))
    // setCommentList(pre => [...pre].sort((a, b) => b.id - a.id))
  }

  // 表单绑定
  const initialValues = {
    username: "张三",
    password: "123456",
  };
  const [values, setValues] = useState(initialValues);
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setValues({
      ...values,
      [name]: value,
    });
    console.log('values', values)
  }
  return (
    <div>
      <button onClick={hanldClick}>修改 变量：{count}</button>
      <button onClick={ChangeForm}>修改对象：{form.name}</button>
      <button onClick={changeArr}>修改数组</button>
      <ul>
        {commentList.map(item =>
          <li
            onClick={() => { changeType(item.type) }}
            style={{ color: type == item.type && 'red' }}
            // className={`oneClass ${type == item.type && 'active'}`}
            key={item.id}>
            {item.id}-{item.name}
          </li>)}
      </ul>
      <div>
        <p>受控表单绑定</p>
        姓名<input type="text"
          value={values.username}
          onChange={handleInputChange}
          name="username"
        /> <br />
        密码<input type="text"
          value={values.password}
          onChange={handleInputChange}
          name="password"
        />

      </div>
    </div>
  );
};

export default UseState;